import envConfig from './env.js'
//服务器请求地址 
const baseUrl = envConfig[process.env.ENV_TYPE].baseUrl

import {
	cleanLogin,
	getTicket
} from './auth';

export default {
	config: {
		baseUrl,
		appCode: envConfig[process.env.ENV_TYPE].appCode,
		header: {
			token: uni.getStorageSync('userToken') || ""
		}

	},
	showToast: (msg) => {
		uni.showToast({
			title: msg || '请求失败',
			icon: 'none',
			duration: 2000
		})
	},
	//封装uni.request()
	request(options) {
		this.config.header.token = uni.getStorageSync('userToken') || "";
		options.header = this.config.header
		options.url = this.config.baseUrl + options.url
		if (options.url === '/web/auth/login') {
			options.data = {
				...(options.data || {}),
				ticket: getTicket(),
				app_code: this.config.appCode
			}
		} else {
			options.data = {
				...(options.data || {}),
			}
		}

		uni.showLoading({
			title: '加载中'
		})
		return new Promise((resolve, reject) => {
			//书写异步操作的代码
			uni.request({
				...options,
				success: res => {
					uni.hideLoading()
					if (res.statusCode === 200) {
						if (res.data.code === 0 || res.data.code === 1) {
							resolve(res.data)
						} else if (res.msg == '获取ticket异常!!!') {
							// 清除本地缓存
							uni.removeStorageSync('ticket');
							uni.removeStorageSync('userInfo');
						} else {
							this.showToast(res.msg)
							reject(res)
						}
					} else {
						this.showToast(res.msg)
						reject(res)
					}
				},
				fail: err => {
					cleanLogin()
					uni.hideLoading()
					reject(err)
				}
			})
		}).catch(err => {
			console.log(err)
		})
	},
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}
}